package com.tc.flutter_demo.receiver;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.widget.Toast;

import java.util.HashMap;
import java.util.Map;

import io.flutter.plugin.common.BasicMessageChannel;
import io.flutter.plugin.common.EventChannel;
import io.flutter.plugin.common.MethodChannel;

public class MyReceiver extends BroadcastReceiver {
    private BasicMessageChannel<Object> mMessageChannel;
    private EventChannel.EventSink mEventSink;
    private MethodChannel mMethodChannel;
    private Handler mHandler;

    public MyReceiver(Handler mHandler, MethodChannel mMethodChannel,
                      EventChannel.EventSink mEventSink, BasicMessageChannel<Object> mMessageChannel) {

        this.mMethodChannel = mMethodChannel;
        this.mEventSink = mEventSink;
        this.mHandler = mHandler;
        this.mMessageChannel = mMessageChannel;
    }

    @Override
    public void onReceive(Context context, Intent intent) {
        Toast.makeText(context, "接收到自定义的广播", Toast.LENGTH_SHORT).show();
        mHandler.post(() -> {
            Map<String, Object> resultMap2 = new HashMap<>();
            resultMap2.put("message", "android 主动调用 flutter test 方法");
            resultMap2.put("code", 200);
            if (mMessageChannel != null) {
                // 向Flutter 发送消息
                mMessageChannel.send(resultMap2, new BasicMessageChannel.Reply<Object>() {
                    @Override
                    public void reply(Object o) {
                        System.out.println("android onReply: " + o);
                    }
                });
            }
            if (mMethodChannel != null) {
                //向Flutter 发送消息
                mMethodChannel.invokeMethod("test2", resultMap2);
            }
            if (mEventSink != null) {
                mEventSink.success(resultMap2);
            }
        });
    }
}